package com.topisv.tms.web.stock.outstorage;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.stock.oustorage.OutstorageBill;
import com.topisv.tms.entity.stock.oustorage.OutstorageBillItem;
import com.topisv.tms.entity.stock.oustorage.OutstorageBox;
import com.topisv.tms.entity.stock.oustorage.OutstorageBoxItem;
import com.topisv.tms.entity.stock.oustorage.OutstorageSendTask;
import com.topisv.tms.repository.stock.outstorage.OutstorageBillItemDao;
import com.topisv.tms.repository.stock.outstorage.OutstorageBoxItemDao;
import com.topisv.tms.repository.stock.outstorage.OutstorageSendTaskDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.outstorage.OutstorageBillService;
import com.topisv.tms.service.stock.outstorage.OutstorageBoxItemService;
import com.topisv.tms.service.stock.outstorage.OutstorageBoxService;
import com.topisv.tms.service.stock.outstorage.OutstorageSendTaskService;
import com.topisv.tms.utils.JsonUtil;

/**
 * 出库发货任务_control
 * @author ch
 */
@Controller
@RequestMapping(value = "/outstorageSendTask")
public class OutstorageSendTaskController {

	private static final Logger logger = LoggerFactory.getLogger(OutstorageSendTaskController.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private OutstorageSendTaskService outstorageSendTaskService;
	@Autowired
	private OutstorageBoxItemService outstorageBoxItemService;
	@Autowired
	private OutstorageBoxService outstorageBoxService;
	@Autowired
	private OutstorageBillService outstorageBillService;

	@Autowired
    private OutstorageBillItemDao outstorageBillItemDao;
	
	@Autowired
	private OutstorageSendTaskDao outstorageSendTaskDao;
	
	@Autowired
	private OutstorageBoxItemDao outstorageBoxItemDao;
	/**
	 * 导向发货任务列表页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toSendTaskListPage")
	public String toSendTaskListPage(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
		    
		    //查找我的任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("workerUuid", curUser.jobuuid);
		    param_my.put("status", "myTask");
		    List<OutstorageSendTask> myTaskList=this.outstorageSendTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myTaskList",myTaskList);
		    
		    //如果是paiu用户,初始化数据
			if("paiu".equals(curUser.userType)){
				//未分配的任务
			    Map<String, Object> param_untaked=new HashMap<String, Object>();
			    param_untaked.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
			    param_untaked.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param_untaked.put("status", "undo"); 
			    List<OutstorageSendTask> untakedTaskList=this.outstorageSendTaskService.loadTaskByParam(param_untaked);
			    model.addAttribute("untakedTaskList",untakedTaskList);
			}
		    
		    //如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				
				String customerCode=customerList.get(0).getCustomerCode();
				model.addAttribute("_customerCode",customerCode);
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//未分配的任务
			    Map<String, Object> param_untaked=new HashMap<String, Object>();
			    param_untaked.put("customerCodes", customerCode);
			    param_untaked.put("status", "undo"); 
			    List<OutstorageSendTask> untakedTaskList=this.outstorageSendTaskService.loadTaskByParam(param_untaked);
			    model.addAttribute("untakedTaskList",untakedTaskList);
				
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/outstorage/outstorageSendTaskList";
	}
	
	
	/**
	 * 查询发货任务列表
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "v2_querySendTaskList")
	public String querySendTaskList(Model model, ServletRequest request, ServletResponse response) throws Exception {
		try {
		
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//查找我的拣货任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("workerUuid", curUser.jobuuid);
		    param_my.put("status", "myTask"); //任务状态( 1.创建任务 2.已分配拣货任务 3.单据上架（灯光架、拣货车） 4.已拣货 5.已分配包装任务  6.已包装 7.已分配发货任务 8.已发货)
		    List<OutstorageSendTask> myTaskList=this.outstorageSendTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myTaskList",myTaskList);
			
		    //查询未分配的拣货任务
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String) param.get("warehouseCode");
			String customerCode=(String) param.get("customerCode");
			
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			param.put("status", "undo"); 
			
			List<OutstorageSendTask> untakedTaskList = this.outstorageSendTaskService.loadTaskByParam(param);
			model.addAttribute("untakedTaskList", untakedTaskList);
			model.addAttribute("_warehouseCode", warehouseCode);
			model.addAttribute("_customerCode", customerCode);
			
			//初始化仓库数据
			if(StringUtils.isNotBlank(customerCode)){
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/outstorage/outstorageSendTaskList";
	}
	

	/**
	 * 领取发货任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxTakeSendTask")
	@ResponseBody
	public String ajaxTakeSendTask(ServletRequest request,HttpServletResponse response) {
		try {	
			Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			this.outstorageSendTaskService.takeTask(taskId,curUser.jobuuid);
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 导向发货页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toSendTaskPage/{taskId}", method = RequestMethod.GET)
	public String toSendTaskPage(@PathVariable("taskId") Long taskId, Model model) {
		try {

			//发货任务
			OutstorageSendTask  task=this.outstorageSendTaskService.loadTaskById(taskId);
		    model.addAttribute("task", task);
		    
		    //出库单
		    OutstorageBill bill=this.outstorageBillService.loadByBillCode(task.getBillCode());
		    model.addAttribute("bill", bill);
		    
		    //箱子信息
		    List<OutstorageBox> boxList=this.outstorageSendTaskService.loadByTaskCode(task.getBillCode());
		    model.addAttribute("boxList", boxList);
		    
		    //初始页面
			model.addAttribute("tab1", "active");
			model.addAttribute("tab2", "");
			
		    return "stock/outstorage/outstorageSendTask";
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return null;
	}
	
	
	/**
	 * ajax创建箱子
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCreateBox")
	public void ajaxCreateBox(ServletRequest request,HttpServletResponse response) {
		try {
			
			String taskCode=request.getParameter("taskCode");
			
			String boxCode=this.outstorageBoxService.createBox(taskCode);
			
			Map<String,String> map=new HashMap<String, String>();
			map.put("boxCode", boxCode);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
		
		} catch (Exception e) {
			logger.error("error",e);
		}
	}
	
	/**
	 * 删除箱子
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxDelBox")
	@ResponseBody
	public String ajaxDelBox(ServletRequest request,HttpServletResponse response) {
		try {	
			String boxCode=request.getParameter("boxCode"); 
			this.outstorageBoxService.delBox(boxCode);
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}
	}
	
	
	/**
	 * 添加商品
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxAddGoods")
	public void ajaxAddGoods(ServletRequest request,HttpServletResponse response) {
		try {	
			String boxCode=request.getParameter("boxCode");
			String sku=request.getParameter("sku"); 
			Integer num=Integer.valueOf(request.getParameter("num")+""); 
			Long itemId=this.outstorageBoxItemService.addBoxItem(boxCode,sku,num);
			
			Map<String,Long> map=new HashMap<String, Long>();
			map.put("itemId", itemId);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
			
		} catch (Exception e) {
			logger.error("error",e);
		}
	}
	
	/**
	 * 删除商品
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxDelGoods")
	@ResponseBody
	public String ajaxDelGoods(ServletRequest request,HttpServletResponse response) {
		try {	
			Long itemId=Long.valueOf(request.getParameter("itemId")+""); 
			this.outstorageBoxItemService.delGoods(itemId);
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}
	}
	
	
	/**
	 * 保存运输信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxSaveTransInfo")
	@ResponseBody
	public String ajaxSaveTransInfo(ServletRequest request,HttpServletResponse response) {
		try {	
			String driverInfo=request.getParameter("driverInfo");
			String carInfo=request.getParameter("carInfo");
			String outTimeStr=request.getParameter("outTime");
			String remark=request.getParameter("remark");
			String billCode=request.getParameter("billCode");
			
			return this.outstorageBillService.saveTransInfo(driverInfo,carInfo,outTimeStr,remark,billCode);
			
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 完成发货任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCompleteSendTask")
	public void ajaxCompleteSendTask(ServletRequest request,HttpServletResponse response) {
		try {	
			Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
			Map<String,Object> map=this.outstorageSendTaskService.completeTask(taskId);
			
			String json = JsonUtil.getObjectString(map);
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	}
	
	/**
	 * 一键添加箱子
	 * 
	 * @param 
	 * @return 
	 * @throws 
	 * @author <a href=mailto:libin@nryuncang.com>libin</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "addBoxByOneKey")
    @ResponseBody
    public Object addBoxByOneKey(ServletRequest request,HttpServletResponse response) {
        try {   
            String taskCode=request.getParameter("taskCode"); 
            String billCode=request.getParameter("billCode"); 
            String boxCode=this.outstorageBoxService.createBox(taskCode);
            logger.info("addBoxByOneKey param taskCode:{},billCode:{}",taskCode,billCode);
            
            List<OutstorageBoxItem> boxItemList=outstorageBoxItemDao.loadByBillCode(billCode);
            if (null != boxItemList && boxItemList.size() > 0) {
                logger.info("addBoxByOneKey result 不符合一键装箱");
                return "false"; 
            }
            List<OutstorageBillItem> billItemList=this.outstorageBillItemDao.loadByBillCode(billCode);
            for (OutstorageBillItem billItem : billItemList) {
                String sku=billItem.getSku();
                Integer num=billItem.getNum();
                Long itemId=this.outstorageBoxItemService.addBoxItem(boxCode,sku,num);
                billItem.setOutstorageBoxItemId(itemId);
                billItem.setBoxCode(boxCode);
            }
            logger.info("addBoxByOneKey result:{}",billItemList);
            return billItemList;
        } catch (Exception e) {
            logger.error("error",e);
            return "false";
        }
    }
	
}
